// import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:jet_rails/jr_app/jr_views/jr_login/jr_login_controller.dart';
import 'package:jet_rails/jr_app/jr_views/jr_main/jr_main_view.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_blur_container.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_buttons.dart';
import 'package:jet_rails/jr_services/jr_services.dart';
import 'package:jet_rails/jr_utils/jr_debouncer.dart';
import 'package:jet_rails/jr_utils/jr_logger.dart';
import 'package:jet_rails/jr_utils/jr_snippet.dart';
import 'package:jet_rails/jr_utils/jr_toast.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

class JrLoginView extends StatefulWidget {
  const JrLoginView({super.key});

  @override
  State<JrLoginView> createState() => JrLoginViewState();
}

class JrLoginViewState extends State<JrLoginView> {
  int currentLoginType = 0;
  Throttler throttler = Throttler(throttleDuration: const Duration(seconds: 1));
  @override
  void initState() {
    super.initState();
    Get.put(JrLoginController());
    checkATT();
    autoLogin();
  }

  @override
  void dispose() {
    Get.delete<JrLoginController>();
    super.dispose();
  }

  checkATT() async {
    final TrackingStatus status = await AppTrackingTransparency.trackingAuthorizationStatus;
    if (status == TrackingStatus.notDetermined) {
      await AppTrackingTransparency.requestTrackingAuthorization();
    }
  }

  autoLogin() async {
    final able = await JrServices.instance.canAutoLogin();
    if (able) {
      Get.find<JrLoginController>().checkedPrivacyAgreement.value = true;
      EasyLoading.show();
      try {
        final bool loginSuccess = await JrServices.instance.loginProcess();
        if (loginSuccess) {
          goToMainPage();
        }
      } catch (e) {
        return false;
      } finally {
        EasyLoading.dismiss();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          Positioned.fill(
              child: Container(
            alignment: Alignment.bottomCenter,
            decoration: const BoxDecoration(
              image: DecorationImage(image: AssetImage('assets/images/login_bg.png'), fit: BoxFit.fill),
            ),
          )),
          Positioned(bottom: 0, left: 0, right: 0, child: Image.asset('assets/images/login_mask.png')),
          SafeArea(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 56),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  buildFastLogInBtn(),
                  const SizedBox(height: 28),
                  buildAppleSignInBtn(),
                  const SizedBox(height: 58),
                  getPrivacyAgreementSection(),
                  const SizedBox(height: 60),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget buildFastLogInBtn() {
    return CupertinoButton(
      padding: EdgeInsets.zero,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 15),
        decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(
            Radius.circular(12),
          ),
          gradient: LinearGradient(
            colors: [
              Color.fromRGBO(138, 109, 255, 1), 
              Color.fromRGBO(173, 109, 255, 1), 
            ],
            begin: Alignment(0.17, 0.07),
            end: Alignment(0.76, 0.94),
          ),
        ),
        child: Stack(
          children: [
            const SizedBox(width: 24, height: 24, child: Image(image: AssetImage('assets/webp/icon_fast_login.webp'))),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: const [
                Text(
                  'Fast Login',
                  style: TextStyle(color: Colors.white),
                ),
              ],
            ),
          ],
        ),
      ),
      onPressed: () => throttler.call(fastLogin),
    );
  }

  Widget buildAppleSignInBtn() {
    return CupertinoButton(
        padding: EdgeInsets.zero,
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 15),
          decoration: const BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(12))),
          child: Stack(
            children: [
              const SizedBox(
                  width: 24, height: 24, child: Image(image: AssetImage('assets/webp/icon_apple_logo.webp'))),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: const [
                  Text('Sign in with Apple', style: TextStyle(color: Colors.black)),
                ],
              ),
            ],
          ),
        ),
        onPressed: () => throttler.call(loginWithApple));
  }

  Widget getPrivacyAgreementSection() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Obx(() {
          return Checkbox(
            shape: RoundedRectangleBorder(
              side: BorderSide(width: 1, color: Colors.grey.withAlpha(128)),
              borderRadius: const BorderRadius.all(Radius.circular(10)),
            ),
            value: Get.find<JrLoginController>().checkedPrivacyAgreement.value,
            onChanged: (value) {
              Get.find<JrLoginController>().checkedPrivacyAgreement.value = value!;
            },
          );
        }),
        Expanded(child: buildPrivacyRichText()),
      ],
    );
  }

  Widget buildPrivacyRichText() {
    return RichText(
      text: TextSpan(
          text: 'By using our App you agree with our\n',
          style: const TextStyle(color: Colors.white, wordSpacing: 2, fontSize: 12),
          children: [
            TextSpan(
              text: "Term of Use",
              style: const TextStyle(
                  color: Color(0xFF9F68F1),
                  fontSize: 14,
                  decoration: TextDecoration.underline,
                  decorationColor: Color(0xFF9F68F1),
                  decorationThickness: 1),
              recognizer: TapGestureRecognizer()
                ..onTap = () {
                  JrSnippets.tapTermOfUse();
                },
            ),
            const TextSpan(
              text: " and ",
              style: TextStyle(color: Colors.white, fontSize: 12),
            ),
            TextSpan(
              text: "Privacy Policy",
              style: const TextStyle(
                  color: Color(0xFF9F68F1),
                  fontSize: 14,
                  decoration: TextDecoration.underline,
                  decorationColor: Color(0xFF9F68F1),
                  decorationThickness: 1),
              recognizer: TapGestureRecognizer()
                ..onTap = () {
                  JrSnippets.tapPrivacyPolicy();
                },
            ),
            const TextSpan(
              text: ".",
              style: TextStyle(color: Colors.white, fontSize: 12),
            ),
          ]),
    );
  }

  void agreeAndContinue() {
    Get.find<JrLoginController>().checkedPrivacyAgreement.value = true;
    Get.back();
    if (currentLoginType == 1) {
      doAppleLogin();
    } else {
      doFastLogin();
    }
  }

  bool checkPrivacyAgreement() {
    if (Get.find<JrLoginController>().checkedPrivacyAgreement.value == false) {
      Get.dialog(buildDialog());
      return false;
    }
    return true;
  }

  Widget buildDialog() {
    return Center(
      child: JrBlurContainer(
        height: 320.h,
        width: 320.w,
        padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 20.h),
        decoration: BoxDecoration(
            gradient: const LinearGradient(
                colors: [Color(0x7DF29FFF), Color(0x7DA46EFF)], begin: Alignment.topLeft, end: Alignment.bottomRight),
            borderRadius: BorderRadius.circular(12.r)),
        child: Column(children: [
          Image.asset('assets/images/logo.png', height: 64.h),
          SizedBox(height: 8.h),
          Text('JetRails', style: TextStyle(fontSize: 14.sp).merge(JrSnippets.commonTextStyle)),
          SizedBox(height: 20.h),
          buildPrivacyRichText(),
          SizedBox(height: 20.h),
          JrGradientButton(
            height: 40.h,
            width: 180.w,
            text: 'Agree and Continue',
            onTap: agreeAndContinue,
          ),
          SizedBox(height: 20.h),
          JrGradientButton(
            height: 40.h,
            width: 180.w,
            text: 'Cancel',
            gradient: const LinearGradient(colors: [Colors.black26, Colors.black26]),
            onTap: () {
              Get.back();
            },
          )
        ]),
      ),
    );
  }

  void fastLogin() {
    currentLoginType = 0;
    if (checkPrivacyAgreement() == false) {
      return;
    }
    doFastLogin();
  }

  void loginWithApple() async {
    currentLoginType = 1;
    if (checkPrivacyAgreement() == false) {
      return;
    }
    doAppleLogin();
  }

  Future<bool> doFastLogin() async {
    EasyLoading.show(maskType: EasyLoadingMaskType.black);
    bool isLoginSuccess = false;
    try {
      isLoginSuccess = await JrServices.instance.login();
    } catch (e, s) {
      JrLogger.e('error on fast login: $e, $s');
    } finally {
      EasyLoading.dismiss();
    }
    if (isLoginSuccess) {
      goToMainPage();
    } else {
      JrToast.show('Login failed, please try again later.');
    }
    return isLoginSuccess;
  }

  Future<bool> doAppleLogin() async {
    EasyLoading.show(maskType: EasyLoadingMaskType.black);
    bool isLoginSuccess = false;
    AuthorizationCredentialAppleID? credential;
    try {
      credential = await SignInWithApple.getAppleIDCredential(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
      );
      JrLogger.d('Apple credential >>>>>> $credential');
    } catch (e, s) {
      JrLogger.e('error on SignInWithApple.getAppleIDCredential: $e, $s');
    }

    try {
      if (credential != null) {
        isLoginSuccess = await JrServices.instance.login(identityToken: credential.identityToken);
      }
    } catch (e) {
      JrToast.show('Login failed, please try again later.');
    } finally {
      EasyLoading.dismiss();
    }
    if (isLoginSuccess) {
      goToMainPage();
    }
    return isLoginSuccess;
  }

  void goToMainPage() {
    Get.offAll(() => const JrMainView());
  }
}
